package com.yy.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * ClassName: JwtHelper
 * Package: com.yy.utils
 * Description:
 *
 * @Author yy
 * @Create 2023-11-30 18:04
 * @Version 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "jwt.token")
public class JwtHelper {

    private long tokenExpiration; //有效时间,单位毫秒 1000毫秒 == 1秒
    private String tokenSignKey;  //当前程序签名秘钥

    //生成token字符串
    public String createToken(Long userId) {
        System.out.println("tokenExpiration = " + tokenExpiration);
        System.out.println("tokenSignKey = " + tokenSignKey);
        String token = JWT.create()
                .setExpiresAt(new Date(System.currentTimeMillis() + tokenExpiration * 1000 * 60))
                .setPayload("userId", userId)
                .setKey(tokenSignKey.getBytes())
                .setSigner(JWTSignerUtil.hs512(tokenSignKey.getBytes()))
                .sign();
        return token;
    }

    //从token字符串获取userid
    public Long getUserId(String token) {
        try {
            JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs512(tokenSignKey.getBytes()));
        } catch (ValidateException e) {
            return null;
        }
        JWT jwt = JWTUtil.parseToken(token);
        Long userId = Convert.toLong(jwt.getPayload("userId"));
        return userId;
    }


    //判断token是否有效
    public boolean isExpiration(String token) {
        try {
            JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs512(tokenSignKey.getBytes()));
            JWTValidator.of(token).validateDate(DateUtils.getNowDate());
            return false;
        } catch (ValidateException e) {
            return true;
        }

    }
}
